package com.demo.crawler;

import com.demo.entity.Sale;

import com.demo.service.impl.SaleServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

import java.util.List;

/**
 * @author lepdou 2017-06-18
 */
@Service
public class Crawler implements ICrawler{

    private static final String CRAWLER_URL = "http://www.tmsf.com/index.jsp";


    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private SaleServiceImpl saleService;
    @Autowired
    private SaleDataParser saleDataParser;


    public String run() {
    String html = restTemplate.getForEntity(CRAWLER_URL, String.class).getBody();
       // return restTemplate.getForEntity(CRAWLER_URL, String.class).getBody();
    if (StringUtils.isEmpty(html)) {
      return "failed";
    }

    List<Sale> sales = saleDataParser.parse(html);

    if (CollectionUtils.isEmpty(sales)) {
      return "failed";
    }

    saleService.save(sales);
        return sales.toString();
    }

}